<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="工单类型" prop="slaName" style="font-size: 11px; white-space: nowrap;">
        <el-input v-model="queryParams.slaName" placeholder="请输入工单类型" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="响应时间(分钟)" prop="responseTime" style="font-size: 11px; white-space: nowrap;">
        <el-input v-model="queryParams.responseTime" placeholder="请输入响应时间(分钟)" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="解决时间(分钟)" prop="resolutionTime" style="font-size: 11px; white-space: nowrap;">
        <el-input v-model="queryParams.resolutionTime" placeholder="请输入解决时间(分钟)" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="内外部标识" prop="internal" style="font-size: 11px; white-space: nowrap;">
          <el-select v-model="queryParams.internal" placeholder="请选择内外部标识" style="width: 200px;">
            <el-option v-for="item in [{ value: '0', label: '内部' }, { value: '1', label: '外部' }]" :key="item.value"
              :label="item.label" :value="item.value">
            </el-option>
          </el-select>
      </el-form-item>
      
      <!--      <el-form-item label="所属部门ID" prop="deptId">
        <el-input
          v-model="queryParams.deptId"
          placeholder="请输入所属部门ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['system:setting:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:setting:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:setting:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['system:setting:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="settingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!--  <el-table-column label="ID" align="center" prop="slaId" />-->
      <el-table-column label="工单类型" align="center" prop="slaName" width="100"/>
      <el-table-column label="响应时间(分钟)" align="center" prop="responseTime" width="120"/>
      <el-table-column label="解决时间(分钟)" align="center" prop="resolutionTime" width="120"/>
      <el-table-column label="责任人组" align="center" prop="relationIds" width="500">
        <template #default="scope">
          <el-tooltip effect="dark" placement="top" popper-class="custom-tooltip" >
            <template #content>
              {{ 
                (scope.row.relationIds || '')
                  .split(',')
                  .map(id => {
                    function findLabel(nodes, id) {
                      if (!nodes) return '';
                      for (const node of nodes) {
                        if (node.id == id) return node.label;
                        if (node.children) {
                          const label = findLabel(node.children, id);
                          if (label) return label;
                        }
                      }
                      return '';
                    }
                    return findLabel(userOptions, id);
                  })
                  .filter(Boolean)
                  .join('/')
              }}
            </template>
            <span style="display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden;">
              {{
                (scope.row.relationIds || '')
                  .split(',')
                  .map(id => {
                    function findLabel(nodes, id) {
                      if (!nodes) return '';
                      for (const node of nodes) {
                        if (node.id == id) return node.label;
                        if (node.children) {
                          const label = findLabel(node.children, id);
                          if (label) return label;
                        }
                      }
                      return '';
                    }
                    return findLabel(userOptions, id);
                  })
                  .filter(Boolean)
                  .join('/')
              }}
            </span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="description" width="300"/>
      <el-table-column label="内外部工单" align="center" prop="internal" width="120">
        <template #default="scope">
          <span>{{ scope.row.internal === '0' ? '内部' : scope.row.internal === '1' ? '外部' : '' }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="所属部门ID" align="center" prop="deptId" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="140">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:setting:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:setting:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="settingRef" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="工单图标" prop="filePath">
          <el-popover
            placement="bottom-start"
            width="400"
            trigger="click"
          >
            <template #reference>
              <el-input
                v-model="form.fileName"
                placeholder="点击选择图标"
                readonly
              >
                <template #prefix>
                  <img
                    v-if="selectedImage"
                    :src="selectedImage"
                    class="preview-thumb"
                  />
                </template>
              </el-input>
            </template>

            <el-input
              v-model="filterKeyword"
              placeholder="请输入图标名称"
              size="small"
              style="margin-bottom: 8px"
            />

            <div class="icon-grid">
              <div
                v-for="item in filteredIcons"
                :key="item.id"
                class="icon-item"
                @click="selectIcon(item)"
              >
                <img :src="item.loadUrl" class="icon-img" />
                <!-- <div class="icon-label">{{ item.name }}</div> -->
              </div>
            </div>
          </el-popover>
        </el-form-item>
        <el-form-item label="工单类型" prop="slaName">
          <el-input v-model="form.slaName" placeholder="请输入工单类型" />
        </el-form-item>
        <el-form-item label="响应时间(分钟)" prop="responseTime">
          <el-input v-model="form.responseTime" placeholder="请输入响应时间(分钟)" style="width: 70%;"/>
          <el-checkbox v-model="form.responseAlarm" label="超时告警" size="large" style="margin-left: 20px;" @change="responseCheck"/>
        </el-form-item>
        <el-form-item label="解决时间(分钟)" prop="resolutionTime">
          <el-input v-model="form.resolutionTime" placeholder="请输入解决时间(分钟)" style="width: 70%;"/>
          <el-checkbox v-model="form.resolutionAlarm" label="超时告警" size="large" style="margin-left: 20px;" @change="resolutionCheck"/>
        </el-form-item>
        <el-form-item label="内外部标识" prop="internal">
          <el-select v-model="form.internal" placeholder="请选择内外部标识" style="flex: 1;">
            <el-option v-for="item in [{ value: '0', label: '内部' }, { value: '1', label: '外部' }]" :key="item.value"
              :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="责任人组选择" prop="relationIds">
          <el-tree-select v-model="form.relationIds" :data="userOptions" :render-after-expand="false" show-checkbox
            :props="{
              value: 'id',
              label: 'label',
              children: 'children',
              // 可选：禁用用户节点选择
              disabled: (data) => {
                if (!data.isUser) return true
                
                if(form.relationIds && form.relationIds.length > 0){
                  const hasDefault = form.relationIds.includes('default')
                  return hasDefault ? data.id !== 'default' : data.id === 'default'
                }else{
                  return false
                }
              }
            }" check-strictly check-on-click-node multiple node-key='id' filterable style="width: 100%"
            placeholder="选择责任人组" />
        </el-form-item>
        <el-form-item label="告警升级时间(分钟)" prop="upgradeTime">
          <el-input v-model="form.upgradeTime" placeholder="请输入告警升级时间(分钟)" style="width: 70%;" :disabled="!form.upgradeAlarm"/>
          <el-checkbox v-model="form.upgradeAlarm" label="升级通知" size="large" style="margin-left: 20px;" @change="upgradeCheck" :disabled="!form.resolutionAlarm && !form.responseAlarm"/>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入描述" />
        </el-form-item>
        <!--        <el-form-item label="所属部门ID" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入所属部门ID" />
        </el-form-item>-->
        <!--        <el-form-item label="删除标识" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标识" />
        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Setting">
import { listSetting, getSetting, delSetting, addSetting, updateSetting } from "@/api/system/setting";
import { iconList } from "@/api/system/icon";
import useUserStore from "@/store/modules/user"
import { deptUserTree } from "@/api/system/role"

const { proxy } = getCurrentInstance();

const settingList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {
    filePath: null,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    slaName: null,
    responseTime: null,
    resolutionTime: null,
    deptId: null,
    internal: null,
  },
  rules: {
    slaName: [
      { required: true, message: "工单类型不能为空", trigger: "blur" }
    ],
    responseTime: [
      { required: false, message: "响应时间(分钟)不能为空", trigger: "blur" }
    ],
    resolutionTime: [
      { required: false, message: "解决时间(分钟)不能为空", trigger: "blur" }
    ],
    internal: [
      { required: true, message: "请选择内外部标识", trigger: "change" }
    ],
    relationIds: [
      { required: true, message: "请选择内责任人组选择", trigger: "change" }
    ],
    description: [
      { required: true, message: "描述不能为空", trigger: "blur" }
    ],
    upgradeTime: [
      { required: false, message: "告警升级时间(分钟)不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
const imgOptions = ref([])
function iconLists() {
  iconList({}).then(response => {
    imgOptions.value = response.data;
  });
}
iconLists()

const selectedImage = ref('')
const filterKeyword = ref('')

watch(() => form.value.filePath, (val) => {
  const item = imgOptions.value.find(i => i.loadUrl === val)
  selectedImage.value = item?.loadUrl || ''
})

const filteredIcons = computed(() =>
  imgOptions.value.filter(item =>
    item.name.toLowerCase().includes(filterKeyword.value.toLowerCase())
  )
)

function selectIcon(item) {
  form.value.fileName = item.name
  form.value.filePath = item.loadUrl
}

const userOptions = ref([])

useUserStore().getInfo().then((res) => {
  // 获取责任人
  deptUserTree({ deptId: res.user.dept.deptId }).then((response) => {
    if (response.code == 200) {
      response.data.isParent = true
      userOptions.value = [transformDeptTree(response.data, true), { value: 'default', isUser: true, id: 'default', label: '按排班及其责任人执行' }]
    }
  })
})

const shouldUpdateDisabled = ref(false)

const onCheckChange = (v) => {
  const hasDefault = form.value.relationIds.includes('default')

  if (shouldUpdateDisabled.value !== hasDefault) {
    shouldUpdateDisabled.value = hasDefault
    nextTick(() => {
      userOptions.value = [...userOptions.value]
    })
  }

}

/** 查询【请填写功能名称】列表 */
function getList() {
  loading.value = true;
  listSetting(queryParams.value).then(response => {
    settingList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    slaId: null,
    slaName: null,
    responseTime: null,
    resolutionTime: null,
    deptId: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    description: null,
    filePath: null,
    internal: null,
    relationIds: [],
    responseAlarm: false,
    resolutionAlarm: false,
    upgradeAlarm: false,
  };
  proxy.resetForm("settingRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.slaId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加工单类型";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _slaId = row.slaId || ids.value
  getSetting(_slaId).then(response => {
    let data = JSON.parse(JSON.stringify(response.data))
    if (data.relationIds) {
      data.relationIds = data.relationIds.split(',').map(item => {
        if (item === 'default') {
          return item
        } else {
          return Number(item)
        }
      })
    }
    form.value = data;
    form.value.responseAlarm = strToBoolean(data.responseAlarm)
    form.value.resolutionAlarm = strToBoolean(data.resolutionAlarm)
    form.value.upgradeAlarm = strToBoolean(data.upgradeAlarm)
    
    open.value = true;
    title.value = "修改工单类型";
  });
}
function strToBoolean(str) {
  return str === 'true'; // 只有字符串是 'true' 时返回 true，其他情况（包括 'false'）返回 false
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["settingRef"].validate(valid => {
    if (valid) {
      let params = JSON.parse(JSON.stringify(form.value))
      params.relationIds = params.relationIds.join(',')
      if (form.value.slaId != null) {
        updateSetting(params).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSetting(params).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _slaIds = row.slaId || ids.value;
  const _slaIdNames = row.slaName || slaNames.value;
  proxy.$modal.confirm('是否确认删除工单类型名称为"' + _slaIdNames + '"的数据项？').then(()=> {
    delSetting(_slaIds).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/setting/export', {
    ...queryParams.value
  }, `setting_${new Date().getTime()}.xlsx`)
}

getList();


function transformDeptTree(deptNode, isRoot = false) {
  // 1. 处理当前部门节点
  const transformedNode = {
    id: deptNode.deptId,
    label: deptNode.deptName,
    isUser: deptNode.isParent === true ? false : true,
    children: []
  };

  // 2. 合并用户到同层级children（优先处理用户）
  if (deptNode.userList?.length > 0) {
    transformedNode.children.push(
      ...deptNode.userList.map(user => ({
        id: user.userId,
        label: `${user.nickName} (${user.userName})`,
        isUser: true
      }))
    );
  }

  // 3. 递归处理子部门
  if (deptNode.children?.length > 0) {
    transformedNode.children.push(
      ...deptNode.children.map(child => transformDeptTree(child))
    );
  }

  // 4. 根节点特殊处理：将第一个子元素移到最前
  if (isRoot && transformedNode.children.length > 0) {
    const firstChild = transformedNode.children.shift();
    transformedNode.children.unshift(firstChild); // 显式确保顺序
  }

  // 5. 处理空children
  if (transformedNode.children.length === 0) {
    delete transformedNode.children;
  }

  return transformedNode;
}
// 复选框超时告警逻辑
const responseCheck = (val) =>{
  // 如果复选框是true，那么将响应时间的input变成必填
  if(val){
    rules.value.responseTime[0].required = true
  }else{
    rules.value.responseTime[0].required = false
  }
}
// 复选框超时告警逻辑
function resolutionCheck(val){
  // 如果复选框是true，那么将解决时间的input变成必填
  if(val){
    rules.value.resolutionTime[0].required = true
  }else{
    rules.value.resolutionTime[0].required = false
  }

}
// 复选框超时告警逻辑
function upgradeCheck(val){
  // 复选框是false，将告警升级时间数据清空
  if(!val){
    form.value.upgradeTime = ''
    rules.value.upgradeTime[0].required = false
  }else{
    rules.value.upgradeTime[0].required = true
  }
}
</script>
<style scoped>
.preview-thumb {
  width: 20px;
  height: 20px;
  margin-right: 4px;
}
.icon-grid {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 12px;
  max-height: 240px;
  overflow-y: auto;
}
.icon-item {
  text-align: center;
  cursor: pointer;
  display: flex;
  flex-direction: row;
  align-items: center;
}
.icon-img {
  width: 32px;
  height: 32px;
  margin-bottom: 4px;
}
.icon-label {
  font-size: 12px;
  color: #666;
  word-break: break-word;
}
</style>
<style>
/* 全局样式文件 */
.custom-tooltip {
  max-width: 500px !important;
  word-break: break-all !important;
  line-height: 1.5;
  background: #2c3e50; /* 深色背景示例 */
  color: #ecf0f1; /* 文字颜色 */
  padding: 12px;
  border-radius: 4px;
}
</style>
